package com.gitee.feizns.explore.data_structure.tree.bs.mid;

import java.util.HashMap;
import java.util.Map;

/**
 * @author feizns
 * @since 2020/3/18
 */
public class SumEvenGrandparent {

    public static void main(String[] args) {

    }

    static Map<TreeNode, TreeNode> parents = new HashMap<>();

    public static int sumEvenGrandparent(TreeNode root) {
        return dfs(root);
    }

    private static int dfs(TreeNode root) {
        int ret = 0;
        if ( root != null ) {
            if ( root.val % 2 == 0 ) {
                if ( root.left != null ) {
                    if ( root.left.left != null )
                        ret += root.left.left.val;
                    if ( root.left.right != null )
                        ret += root.left.right.val;
                    ret += dfs(root.left);
                }
                if ( root.right != null ) {
                    if ( root.right.left != null )
                        ret += root.right.left.val;
                    if ( root.right.right != null )
                        ret += root.right.right.val;
                    ret += dfs(root.right);
                }
            }
        }
        return ret;
    }

//    private static int dfs(TreeNode root, TreeNode parent) {
//        int ret = 0;
//        if ( root != null ) {
//            TreeNode gp = parents.get(parent);
//            if ( gp != null && gp.val % 2 == 0 )
//               ret += root.val;
//            if ( root.left != null )
//                parents.put(root.left, root);
//            if ( root.right != null )
//                parents.put(root.right, root);
//            ret += dfs(root.left, root);
//            ret += dfs(root.right, root);
//        }
//        return ret;
//    }

}
